package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.DTO.DishDto;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.Category.CategoryService;
import com.itheima.reggie.service.Dish.DishService;
import com.itheima.reggie.service.DishFlavor.DishFlavorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 菜品 新增管理
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> dishPage(int page,int pageSize,String name){
        //分页构造器
        Page<Dish> pageinfo = new Page<>(page,pageSize);
        Page<DishDto> pageDishDto = new Page<>();
        //添加排序
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加条件 构造器
        lambdaQueryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行查询
        dishService.page(pageinfo,lambdaQueryWrapper);
        //对象深拷贝
        BeanUtils.copyProperties(pageinfo,pageDishDto,"records");
        List<Dish> dishList = pageinfo.getRecords();
        List<DishDto> dishDtoList =  dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId(); // 分类id
            // 根据 id 查询分类对象
            Category byId = categoryService.getById(categoryId);
            if (byId != null){
                dishDto.setCategoryName(byId.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        pageDishDto.setRecords(dishDtoList);
        return R.success(pageDishDto);
    }

    /**
     * 根据 id 查询 菜品信息 and 口味信息
     * @param id
     * @return
     */
   @GetMapping("/{id}")
    public R<DishDto> DishID(@PathVariable Long id){
       log.info("修改菜品分类id"+id);
       DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
       return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品 以及 菜品口味
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> PutDish(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }
    /**
     * 查询对应菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件 查询状态为1(起售状态) 的菜品
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lambdaQueryWrapper);
        List<DishDto> dishDtoList =  list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId(); // 分类id
            // 根据 id 查询分类对象
            Category byId = categoryService.getById(categoryId);
            if (byId != null){
                dishDto.setCategoryName(byId.getName());
            }
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId,id);
            dishDto.setFlavors(dishFlavorService.list(lambdaQueryWrapper1));
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }
    @DeleteMapping
    @Transactional
    public R<String> deleteDish(@RequestParam("ids") Long[] id){
        log.info("要删除的id:{}",id);
        for (Long l : id) {
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,l);
            dishFlavorService.remove(lambdaQueryWrapper);
        }
        List<Long> list = Arrays.asList(id);
        dishService.removeByIds(list);
        return R.success("删除成功");
    }

    @PostMapping("/status/{s}")
    public R<String> Upstatus(@PathVariable("s") Integer status,@RequestParam("ids") Long[] id){
        log.info("状态:{}",status);
        for (Long l : id) {
            Dish byId = dishService.getById(l);
            byId.setStatus(status);
            dishService.updateById(byId);
        }
        return R.success(status == 0 ?"以停售":"启售");
    }

}
